sleep(0)、usleep(0)与sched | 您所在的位置:网站首页 › pthread yield函数 › sleep(0)、usleep(0)与sched |
结论: 如果你是为了耗掉一个机器周期 ,那直接asm ("nop") , 如果是为了让权,建议把 所有使用 usleep(0) 换成 sched_yield() ;
最近发现很多hpc 领域的MPI程序中在用usleep(0) ,比较差异。 后来问了之前做hpc 的同事 得到的答复是 一般用usleep(0) 的主要目的应该是: CPU交出当前线程的执行权,让CPU去执行其他线程。也就是放弃当前线程的时间片,转而执行其他线程
我感觉很诧异。 Usleep(0) 来做这个事情 是POSIX要求的 还是一个意外的发现呢? 于是有2个问题 1 :usleep(0) 能不能让权, 2 :如果可以,那么和sched_yield 比到底谁更合适
我先man了一下usleep(0) 在linux上 , NOTES The type useconds_t is an unsigned integer type capable of holding integers in the range [0,1000000]. Programs will be more portable if they never mention this type explicitly. Use #include ... unsigned int usecs; ... usleep(usecs); The interaction of this function with the SIGALRM signal, and with other timer functions such as alarm(2), sleep(3), nanosleep(2), setitimer(2), timer_create(2), timer_delete(2), timer_getoverrun(2), timer_gettime(2), timer_settime(2), ualarm(3) is unspecified.
先来看几个奇怪的现象:
执行shell usleep 0 会明显的看到调用了
难道 usleep(0) = sched_yield?
而
执行shell usleep x (x!=0 ) 会去调用naonsleep 这就比较合理了, 之前猜测 usleep 就应该是调用了 nanosleep ,
然后写一个 c 函数调用来看看 会发现 无论是0 还是 !0 都是调用的
这就比较合理了, 看了glibc源码 也验证了确实是 封装naosleep
那第一个问题在linux 上就变成 naosleep(0,0) 是不是会去让权了, 他和sheld_yield 的区别。
在.18 之后 应该naosleep 都是基于 hrtimer的机制实现了 ( ============================================================== C代码do_nanosleep(struct hrtimer_sleeper *t, enum hrtimer_mode mode) { hrtimer_init_sleeper(t, current); do { set_current_state(TASK_INTERRUPTIBLE); hrtimer_start_expires(&t->timer, mode); if (!hrtimer_active(&t->timer)) t->task = NULL; if (likely(t->task)) schedule(); hrtimer_cancel(&t->timer); mode = HRTIMER_MODE_ABS; } while (t->task && !signal_pending(current)); __set_current_state(TASK_RUNNING); return t->task == NULL; }======= 补充一个 在2.6.9内核 或者可能之前的glibc实现中 usleep(0) 如果是基于 select (0) 这样的实现 在判断入参是0 之后会离开返回 不会调用 schelduer()的
=====================================================================
)
根据nanosleep 的 syscall ,发现
很明显的有 schedule(), 于是可以确定 usleep(0) 如果一切顺利确实会让权,那么和sched_yield比呢
于是写了一个 main
C代码 #include #include int main(){ int j ; for(j=0; j |
CopyRight 2018-2019 实验室设备网 版权所有 |